import {createPage,base, high, ajax, getMultiLang} from 'nc-lightapp-front';
import requestApi from './requestApi';
import 'src/erm/sscrppublic/common/components/globalPresetVar';
import {setTableGroupExtendCol,setTableExtendCol} from 'src/erm/sscrppublic/common/components/bill';
import attachments from 'uap/common/components/getAttachmentInfo';
import { zzhllxLogic } from './utils'
import _ from 'lodash-es'

const { getAttachments, getAttachmentsInfo } = attachments;

//import buttonTpl from './buttonTpl';


let {NCPopconfirm} = base;
const head1 = window.presetVar.head.head1;
const body1 = window.presetVar.body.body1;
const body2 = window.presetVar.body.body2;
const {Refer} = high,
{getRefer} = Refer; // 获取公共参照的方法

let pageButton = presetVar.pageButton;
const statusVar = presetVar.status;
let buttonTpl = '';
let pagecode = '';
let  appcode = '';
let multiJson = {};
export default function (props) {

    let _this = this;
    let pageStatus = props.getUrlParam('status');
    pagecode = (props.getUrlParam("pagecode")==undefined||props.getUrlParam("pagecode")=='')?props.getSearchParam("p"):props.getUrlParam("pagecode");
    appcode = (props.getUrlParam("appcode")==undefined||props.getUrlParam("appcode")=='')?props.getSearchParam("c"):props.getUrlParam("appcode");
    
    props.createUIDom(
        {
              pagecode: pagecode,//页面编码
              appcode: appcode//小应用编码
        },
        (data) => {
            getMultiLang({moduleId: 2011, domainName: 'erm',currentLocale: 'simpchn', callback: (json) => {
                multiJson = json;
            let meta = data.template;

            // 全局化组织汇率类型
            let zzhllxs = meta.head.items.find((item,index) => {
                return item.attrcode === "zzhllx.rate_category"
            })
            window.presetVar.zzhllxs = zzhllxs && zzhllxs.options
            props.use.cardTable(..._.keys(meta.gridrelation));

            props.meta.setMeta(meta)

            let id = this.props.getUrlParam('id') ? this.props.getUrlParam('id') : this.state.billId;
            id = id == "" ? 0 : id;
            getAttachments(id).then(lists => {
                if (lists.length == 0) {
                    lists = 0;
                }
                props.button.setButtonTitle('fileManager', json['201102HKD-0009'] + ' ' + lists + ' ');//附件
            })

            buttonTpl ={
                button:(data.button==null||data.button==undefined)?[]:data.button
            }
            window.presetVar.pageCode = pagecode;
            let bodys = Object.keys(meta.gridrelation);
            for(var i=1;i<= bodys.length;i++){
                window.presetVar.body["body"+i]=bodys[i-1];
            }
            let transtype = "";
            if (data.context.paramMap && data.context.paramMap.transtype) {
                transtype = data.context.paramMap.transtype;
                window.presetVar.tradetype= props.getUrlParam("tradetype")==null||props.getUrlParam("tradetype")==''?transtype:props.getUrlParam("tradetype");    
                this.setState({ transtype_name: data.context.paramMap.transtype_name });
            }  
           
            loadbill.call(this,meta);
        }})
        }        
    );  



}

async function loadbill (meta) {
    await getAttachmentControl()    
    
    let props = this.props;
    let pageStatus = props.getUrlParam('status');
    let billdata = setDefData(meta);
        let userjson = {
            "pagecode": pagecode,
            "appcode":appcode
        };
    billdata.userjson=JSON.stringify(userjson);

    if(pageStatus == statusVar.edit || pageStatus == statusVar.browse){
        render.call(this, meta);
        let billdata = {};
        billdata.openbillid = props.getUrlParam("id")==undefined ? props.getUrlParam("billid"):props.getUrlParam("id");
        billdata.tradetype = props.getUrlParam("tradetype")||window.presetVar.tradetype;
        billdata.uid = "1001Z3100000000000AE";//这里以后从session中获取
        billdata.pagecode = pagecode;
        requestApi.viewBill({
            data:billdata,
            meta:meta,
            props:props,
            success:(data) =>{
                props.meta.addMeta(meta)
                props.form.setAllFormValue({[presetVar.head.head1]:data.head[presetVar.head.head1]});
                //设置表体数据
                Object.values(presetVar.body).forEach((body) =>{
                    if(data.bodys[body]){
                        props.cardTable.setTableData(body, data.bodys[body]);
                    }
                });
                dataHandle.call(this, data.head["head"],props);
                if(pageStatus == statusVar.browse){
                    props.form.setFormStatus('head', 'browse');
                    Object.values(window.presetVar.body).forEach((body)=>{
                        props.editTable.setStatus(body, 'browse');
                    });
                }
                if(pageStatus == statusVar.edit){
                    let paytarget = props.form.getFormItemsValue("head",['paytarget'])==null?"":props.form.getFormItemsValue("head",['paytarget'])[0].value//收款对象
                    if(paytarget=="0"){
                        props.form.setFormItemsDisabled(
                            "head",{
                                'hbbm':true,
                                'hbbm_v':true,
                                'customer':true,
                                'customer_v':true,
                                'receiver':false,
                                'custaccount':true,
                                'freecust':true
                            }
                        );
                    }else if(paytarget=="1"){
                        props.form.setFormItemsDisabled(
                            "head",{
                                'receiver':true,
                                'customer':true,
                                'hbbm':false,
                                'customer_v':true,
                                'hbbm_v':false,
                                'custaccount':false,
                                'freecust':false
                            }
                        );
                    }else if(paytarget=="2"){
                        props.form.setFormItemsDisabled(
                            "head",{
                                'hbbm':true,
                                'hbbm_v':true,
                                'receiver':true,
                                'customer':false,
                                'customer_v':false,
                                'custaccount':false,
                                'freecust':true
                            }
                        );
                    }
                    props.editTable.setStatus(window.presetVar.body.body1, 'browse');
                }
                this.toggleAuditSideBar()
            }
        });
    }else {
        let transferIds = props.transferTable.getTransferTableSelectedId("head");
        let addtype = props.getUrlParam('addtype');
        let dztzinfo = {
            dztz_batch : props.getUrlParam('dztz_batch'),
            dztz_billno : props.getUrlParam('dztz_billno'),
            dztz_billid : props.getUrlParam('dztz_billid'),
            dztz_summary : props.getUrlParam('dztz_summary'),
        };
        userjson = {
            "dztzinfo":dztzinfo,
            "pagecode": pagecode,
            "addType":addtype,
            "pulldata":transferIds
        };
        billdata.userjson=JSON.stringify(userjson);
        render.call(this, meta);
        initData.call(this,meta,billdata).then(() => {
            let paytarget = props.form.getFormItemsValue("head",['paytarget'])==null?"":props.form.getFormItemsValue("head",['paytarget'])[0].value//收款对象
            if(paytarget=="0"){
                props.form.setFormItemsDisabled(
                    "head",{
                        'hbbm':true,
                        'customer':true,
                        'hbbm_v':true,
                        'customer_v':true,
                        'receiver':false,
                        'custaccount':true,
                        'freecust':true
                    }
                );
            }else if(paytarget=="1"){
                props.form.setFormItemsDisabled(
                    "head",{
                        'receiver':true,
                        'customer':true,
                        'hbbm':false,
                        'customer_v':true,
                        'hbbm_v':false,
                        'custaccount':false,
                        'freecust':false
                    }
                );
            }else if(paytarget=="2"){
                props.form.setFormItemsDisabled(
                    "head",{
                        'hbbm':true,
                        'hbbm_v':true,
                        'receiver':true,
                        'customer':false,
                        'customer_v':false,
                        'custaccount':false,
                        'freecust':true
                    }
                );
            }
            props.editTable.setStatus(window.presetVar.body.body1, 'browse');
            this.toggleAuditSideBar()
        });
    }
}

function initData(meta,billdata) {
    let props = this.props;
    return new Promise((resolve, reject) => {
        // TOP NCCLOUD-91597 校验报销标准取模板时需要使用模板ID chengwbc ADD
        billdata.templetid = meta.pageid;
        // BTM NCCLOUD-91597 校验报销标准取模板时需要使用模板ID
        requestApi.loaddata({
            meta:meta,
            props:props,
            data: billdata,
            success: (data) => {
                props.meta.addMeta(meta)
                if(props.getUrlParam('addtype') == "pull"){
                    props.form.setAllFormValue({[head1]: data.head[head1]});
                    //设置表体数据
                    props.cardTable.setTableData(body1, data.bodys[body1]);
                    props.cardTable.setTableData(body2, data.bodys[body2]);
                    //处理按钮相关状态
                    dataHandle.call(this, data.head[head1], props);
                }
                
                getAttachmentControl()
                resolve();
            }
        });
    });

}

async function getAttachmentControl() {
    //请求附件控制参数
    return new Promise((resolve, reject) => {
        requestApi.getAttachmentControlParams({
            data: { transtypecode: window.presetVar.tradetype },
            success: (data) => {
                // data.enablemodifyaccessory  审批中是否允许修改
                // data.mustuploadaccessory 是否必须上传附件
                window.presetVar.attachmentControl = {
                    modify: data.enablemodifyaccessory,
                    necessary: data.mustuploadaccessory
                }
                resolve()
            }
        })
    })
}

function setDefData(meta) {
    let json={"head":{},"bodys":{}};
    json.head={
      "pageid":"nc.vo.ep.bx.BXHeaderVO"
    };
    json.head.head={
        "areaType": "form",
        "areacode": "head",
        "rows": []
    };
    let body={};
    for(let table in meta.gridrelation){
        body[table]={
            "areaType": "table",
            "areacode": table,
            "rows": []
        };
        let bodyrowValue={};
        meta[table].items.forEach((item) =>{
                let code = item.attrcode;
                bodyrowValue[code]={
                    "display":null,
                    "value":null
                };
        });
        body[table].rows[0]={
            values:bodyrowValue
        }
    }

    let head_values = {};
    meta.head.items.forEach((item) =>{
        let code = item.attrcode;
        head_values[code]={
            "display":null,
            "value":null
        }

    });
    json.head.head.rows[0] = {values:head_values}
    json.bodys=body;
    return json;
    
}

function render(meta) {
    
    let props = this.props;
    let pageStatus = props.getUrlParam('status');
    if(pageStatus == statusVar.add || pageStatus == statusVar.edit){
        buttonTpl.button.map((btg)=>{
            if(btg.key=='buttongroup2'&&btg.children!=null){
                btg.children.map((btn)=>{
                    if(btn.key=='billSubmit'){
                        props.button.setMainButton([pageButton.billSubmit],false);
                        btn['title']= multiJson['2011-0019'];//"保存提交";
                    }
                })
            }
        })
    }else{
        buttonTpl.button.map((btg)=>{
            if(btg.key=='buttongroup2'&&btg.children!=null){
                btg.children.map((btn)=>{
                    if(btn.key=='billSubmit'){
                        props.button.setMainButton([pageButton.billSubmit],true);
                        btn['title']= multiJson['2011-0014'];//"提交";
                    }
                })
            }
        })
    }
    //按钮存入组件
    //注意：以后按钮模板的获取需要用 props.createUIDom 替代。
    props.button.hideButtonsByAreas(head1);
    props.button.setButtons(buttonTpl.button);
        //table扩展按钮弹窗确认框设置
        //props.button.setPopContent(body1 + areaBtnAction.del,'确认要删除该信息吗？') /* 设置操作列上删除按钮的弹窗提示 */

    props.meta.setMeta(meta);

    if(!this.actionByHashChange) {
        setTableGroupExtendCol.bind(this)(props, meta, buttonTpl.button, [], {})
    }


    //肩部按钮可见状态：页面和表格的肩部按钮，这里逻辑根据实际业务实现。
    let btnsVisibleObj = {};
    let isAddOrEditStatus =  pageStatus == statusVar.edit || pageStatus == statusVar.add;
    let isBrowseStatus = pageStatus == statusVar.browse;
    for (let btnKey in pageButton) {
        if (btnKey == pageButton.pageSave || btnKey === pageButton.fileManager || btnKey === pageButton.save_temp) { //整单保存按钮只在添加和编辑态显示
            btnsVisibleObj[btnKey] = isAddOrEditStatus;
        } else if (btnKey == pageButton.pageCancel) { //取消按钮所有状态都显示
            btnsVisibleObj[btnKey] = true;
        } else if(btnKey == pageButton.pageCjk || btnKey == pageButton.pageFyyt){
            btnsVisibleObj[btnKey] = isAddOrEditStatus;
        }else { //其它按钮在浏览态显示
            btnsVisibleObj[btnKey] = isBrowseStatus;
        }
    }
    if (isAddOrEditStatus) { //添加或编辑态 隐藏下列按钮
        btnsVisibleObj[pageButton.save_temp] = true;
    }
    if(isBrowseStatus){
        btnsVisibleObj[pageButton.save_temp] = false;
    }

    props.button.setButtonsVisible(btnsVisibleObj);
    switch(pageStatus) {
        case statusVar.edit:
        case statusVar.add:
            props.form.setFormStatus('head', 'edit');
            Object.values(window.presetVar.body).forEach((body)=>{
                props.editTable.setStatus(body, 'edit');
            });
            break;
        case statusVar.browse:
            props.form.setFormStatus('head', 'browse');
            Object.values(window.presetVar.body).forEach((body)=>{
                props.editTable.setStatus(body, 'browse');
            });
            break;
    }
}

function dataHandle(head,props) {
    //新增汇率适配逻辑，业务单据中的币种与组织本币一致时，汇率及汇率类型不可修改
    let currentrow_bzbm = props.form.getFormItemsValue('head','bzbm');
    //组织汇率类型
    let rate_category =  props.form.getFormItemsValue('head','zzhllx.rate_category'); 
    zzhllxLogic(currentrow_bzbm,rate_category,'head',props,'bbhl')


    const that = this
    //处理数据和按钮状态
    if (head == null || head.rows[0] == null || head.rows[0].values == null) {
        head = props.form.getAllFormValue('head');
    }
    let sxbz = head.rows[0].values.sxbz.value;//单据生效状态
    let spzt = head.rows[0].values.spzt.value;//审批状态
    let djzt =head.rows[0].values.djzt.value//单据状态
    this.setState({djzt})
    let iscostshare = head.rows[0].values.iscostshare.value==null||head.rows[0].values.iscostshare.value==undefined?false:head.rows[0].values.iscostshare.value;
    let btnsVisibleObj = {};
    let pageStatus = props.getUrlParam('status');
    let isAddOrEditStatus =  pageStatus == statusVar.edit || pageStatus == statusVar.add;
    let isBrowseStatus = pageStatus == statusVar.browse;

    let scene = props.getUrlParam('scene');//第三方打开
    let deal = props.getUrlParam("deal");
    for (let btnKey in pageButton) {
        if (isAddOrEditStatus) { //添加或编辑态 隐藏下列按钮
            btnsVisibleObj[pageButton.billSubmit] = true;
            if(djzt == '1') {
                if(pageStatus == 'add'){
                    btnsVisibleObj["save_temp"] = true;//暂存
                }else if(pageStatus == 'edit'){
                    btnsVisibleObj["save_temp"] = false;//暂存
                }
            }    
        }
        if(isBrowseStatus){
             //浏览态隐藏“取消”按钮
             if(btnKey == 'pageCancel'){
                btnsVisibleObj[pageButton.pageCancel]=false;
             }            
            //来源于审批人门户、作业处理时 显示 ：修改、影像扫描|影像查看、联查预算、联查凭证、更多（联查审批情况、联查单据、附件、关闭/重启、打印）
                if(spzt!=-1 && btnKey == pageButton.pageDel){
                  //提交之后,隐藏删除按钮
                  btnsVisibleObj[btnKey] = false;
                }
                //审批状态为初始态，隐藏收回按钮
                if(btnKey == pageButton.billRecall || btnKey == pageButton.billApprove){
                    if(spzt=="3" && (scene != 'zycx' && scene != 'bzcx' && scene != 'fycx')){
                        btnsVisibleObj[btnKey] = isBrowseStatus;
                    }else{
                        btnsVisibleObj[btnKey] = false;
                    }
                }

                if((scene == 'approve' || scene == 'zycl' || scene == 'approvesce') ){
                    if( ( btnKey == pageButton.pageEdit
                        || btnKey == pageButton.imageShow 
                        || btnKey == pageButton.imageUpload 
                        ||  btnKey == pageButton.pagePrint 
                        || btnKey == pageButton.linkQueryJkbx 
                        || btnKey == pageButton.billApprove )){
                            btnsVisibleObj[btnKey] = isBrowseStatus;
                        }
                        
                    if(btnKey == pageButton.billRecall ){
                        btnsVisibleObj[btnKey] = false;
                    }    
                    if(spzt == 1) {
                        btnsVisibleObj[pageButton.pageEdit] = false
                    }
                }
                //来源于作业查询时 显示 ：影像查看、联查预算、联查凭证、更多（联查审批情况、联查单据、打印）
                else if((scene == 'zycx' || scene == 'bzcx' || scene == 'fycx')){
                    if( (btnKey == pageButton.imageShow 
                        ||  btnKey == pageButton.pagePrint 
                        || btnKey == pageButton.linkQueryJkbx 
                        || btnKey == pageButton.billApprove)
                        || btnKey == pageButton.fileManager){
                            btnsVisibleObj[btnKey] = isBrowseStatus;
                        }                        
                }else{
                    if(!(spzt=="-1" ||spzt==null)){
                        btnsVisibleObj[pageButton.pageEdit] = false;
                    }
                }
                //审批状态为初始态，显示：修改|删除|复制、提交、影像扫描|影像查看、更多（附件、作废、打印）
                if((spzt=="-1" ||spzt==null)
                    && (btnKey == pageButton.pagePrint 
                        || btnKey == pageButton.pageCopy 
                        || btnKey == pageButton.imageShow 
                        || btnKey == pageButton.imageUpload 
                        || btnKey == pageButton.billSubmit 
                        || btnKey == pageButton.billInvalid 
                        || btnKey == pageButton.pageEdit 
                        || btnKey == pageButton.pageDel
                        || btnKey == "buttongroup4"
                        || btnKey == "LinkBudget"
                        || btnKey == "LinkVoucher")){
                    btnsVisibleObj[btnKey] = isBrowseStatus;
                }
                
                
                //已完成单据，隐藏影像扫描，附件管理
                else if (btnKey == pageButton.imageUpload 
                    || btnKey == pageButton.fileManager 
                    || btnKey == pageButton.billApprove){
                    if(sxbz=="1"){
                        btnsVisibleObj[btnKey] = false;
                        if(btnKey === pageButton.billApprove) { //单据已生效,联查审批详情放开
                            btnsVisibleObj[btnKey] = true;
                        }
                    }else{
                        if(scene != 'zycx' && scene != 'bzcx' && scene != 'fycx'){
                            btnsVisibleObj[btnKey] = isBrowseStatus;
                        }
                    }
                }
                if((djzt=="-1"||djzt==null)&&(
                    btnKey == pageButton.billSubmit 
                    || btnKey == pageButton.billRecall 
                    || btnKey == pageButton.billInvalid)){
                    btnsVisibleObj[pageButton.btnKey] = false;
                }
                if(djzt == "-1") {//作废
                    if (btnKey == pageButton.pageCopy  || btnKey == pageButton.pagePrint) {
                        btnsVisibleObj[btnKey] = true;
                    } else {
                        btnsVisibleObj[btnKey] = false;
                    }
                }
                 //暂存后隐藏提交按钮
                if (djzt == "0") {
                    btnsVisibleObj[pageButton.billSubmit] = false;
                }

                if(btnKey==pageButton.pageSave){
                    btnsVisibleObj[btnKey] = false;
                }
                btnsVisibleObj[pageButton.pageCopy] = true;
                 
        }else{
            if (btnKey == pageButton.pageSave 
                || btnKey == pageButton.billSubmit
                || btnKey === pageButton.fileManager 
                || btnKey == 'pageCancel'
                || btnKey == pageButton.save_temp
                ) { //整单保存按钮只在添加和编辑态显示
                btnsVisibleObj[btnKey] = isAddOrEditStatus;
                btnsVisibleObj[pageButton.pageCancel] = isAddOrEditStatus;
            }else{
                btnsVisibleObj[btnKey] = false;
            }
        }

    }
    if(deal!=undefined&&(deal=='handon'||deal=='adjust'||deal=='sscreject'||deal=='handled')){
        btnsVisibleObj[pageButton.pageEdit] = false;
    }

    if(isAddOrEditStatus){
        btnsVisibleObj["LinkBudget"] = false;
        btnsVisibleObj["LinkVoucher"] = false;
        // 编辑态隐藏"更多"按钮,应该隐藏buttongroup4的parent
        // btnsVisibleObj["buttongroup4"] = false;
        btnsVisibleObj["buttongroup4-more"] = false;
    }else{
        btnsVisibleObj["buttongroup4"] = isBrowseStatus;
        //处理还款单浏览态不允许查看凭证和预算
        if(scene == 'approve' || scene == 'approvesce' || scene == 'zycl' || scene == 'zycx' ||scene == 'fycx'){
            btnsVisibleObj[pageButton['linkVoucher']] = isBrowseStatus;
            btnsVisibleObj[pageButton['linkBudget']] = isBrowseStatus;
        }else{
            btnsVisibleObj[pageButton['linkVoucher']] = false;
            btnsVisibleObj[pageButton['linkBudget']] = false;
        }
       
        
        btnsVisibleObj["pagePrint"] = isBrowseStatus;
        btnsVisibleObj["linkQueryJkbx"] = isBrowseStatus;
        if(djzt == '-1') {
            btnsVisibleObj["billInvalid"] = false;
            btnsVisibleObj[pageButton.imageUpload] = false;
        } else {
            btnsVisibleObj["billInvalid"] = isBrowseStatus;
        }
        btnsVisibleObj[pageButton.imageUpload] = isBrowseStatus;
        btnsVisibleObj[pageButton.fileManager] = isBrowseStatus; 
        // 审批状态为提交时,隐藏掉提交按钮
        if(spzt==1 || spzt==2 || spzt==3 ){
            btnsVisibleObj[pageButton.billSubmit] = false;
            btnsVisibleObj[pageButton.billInvalid] = false;
        }
    }
    if(scene == 'zycx' || scene == 'bzcx'||scene == 'fycx'){
        btnsVisibleObj[pageButton.pageEdit] = false;
        btnsVisibleObj[pageButton.imageUpload] = false;
        btnsVisibleObj[pageButton.billSubmit] = false;
        btnsVisibleObj[pageButton.pageDel] = false;
    }

    //来源于报表联查的单据
    if(scene=='sscermlink'){
        for (let btnKey in pageButton) {
            if(  btnKey == pageButton.imageShow  ||  btnKey == pageButton.pagePrint ||  btnKey === pageButton.fileManager || btnKey == "LinkBudget" || btnKey == "LinkVoucher"  )
             {
                btnsVisibleObj[btnKey] = isBrowseStatus;
             }else{
                btnsVisibleObj[btnKey] = false;
            }
        }
    }

    // 审批进行中  提交状态 附件可编辑受控
    if (spzt == 2 || spzt == 3) {
        if (window.presetVar.attachmentControl) {
            that && that.setState({uploaderBtnDisable: !window.presetVar.attachmentControl.modify})
        }
    }else if(spzt == -1) {
            //单据不在审批中,默认可修改
            that && that.setState({uploaderBtnDisable: false})
    }
    if(spzt == "1"){
        btnsVisibleObj["pageMakebill"] = true;//审批中心的制单按钮   
        btnsVisibleObj[pageButton.imageUpload] = false;
        that && that.setState({uploaderBtnDisable: true})
    }else{
        btnsVisibleObj["pageMakebill"] = false;//审批中心的制单按钮   
    }
    if(djzt == "-1") { 
        btnsVisibleObj[pageButton.imageUpload] = false;
        that && that.setState({uploaderBtnDisable: true})
    }
    if (spzt == "3" && djzt == "1") {
        btnsVisibleObj[pageButton.billSubmit] = false;
    }
    props.button.setButtonsVisible(btnsVisibleObj);
}
export { dataHandle }

function routeChange(props) {
    this.actionByHashChange = true
    loadbill.call(this, props.meta.getMeta());
}
export { routeChange }






